package com.gzw.shop.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.gzw.shop.App;
import com.gzw.shop.Contans;
import com.gzw.shop.R;
import com.gzw.shop.bean.Address;
import com.gzw.shop.bean.Province;
import com.gzw.shop.http.OkHttpHelper;
import com.gzw.shop.http.SpotsCallBack;
import com.gzw.shop.msg.BaseRespMsg;
import com.gzw.shop.utils.GetJsonDataUtil;
import com.gzw.shop.utils.ToastUtils;
import com.gzw.shop.widget.ClearEditText;
import com.gzw.shop.widget.GToolbar;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Response;

public class AddressAddActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    GToolbar toolbar;
    @BindView(R.id.edittxt_consignee)
    ClearEditText edittxtConsignee;
    @BindView(R.id.edittxt_phone)
    ClearEditText edittxtPhone;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.ll_city_picker)
    LinearLayout llCityPicker;
    @BindView(R.id.edittxt_add)
    ClearEditText edittxtAdd;

    private Address address;
    private boolean isUpdate = false;

    private ArrayList<Province> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();


    private OptionsPickerView pvOptions;

    private OkHttpHelper helper = OkHttpHelper.getInstance();

    @Override
    public int getLayoutId() {
        return R.layout.activity_address_add;
    }

    @Override
    public void initView() {


        Bundle bunder = getIntent().getExtras();
        if (bunder != null) {
            address = (Address) bunder.get("address");
        }

        if (address != null) {
            isUpdate = true;
            edittxtAdd.setText(address.getAddr());
            edittxtPhone.setText(address.getPhone());
            edittxtConsignee.setText(address.getConsignee());
        }

        toolbar.setRightBtnOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isUpdate) {
                    address.setAddr(txtAddress.getText().toString() + edittxtAdd.getText().toString());
                    address.setConsignee(edittxtConsignee.getText().toString());
                    address.setPhone(edittxtPhone.getText().toString());

                    if (address.getPhone().length() != 11) {
                        ToastUtils.show(AddressAddActivity.this, "手机号格式不正确");
                        return;
                    }
                    updateAddress(address);
                } else {
                    addressAdd();
                }
            }
        });
        toolbar.setIvLeftOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    private void updateAddress(Address address) {

        Map<String, Object> params = new HashMap<>();
        params.put("id", address.getId());
        params.put("consignee", address.getConsignee());
        params.put("phone", address.getPhone());
        params.put("addr", address.getAddr());
        params.put("zip_code", address.getZipCode());
        params.put("is_default", address.getIsDefault());

        helper.post(Contans.API.ADDRESS_UPDATE, params, new SpotsCallBack<BaseRespMsg>(this) {
            @Override
            public void onSuccess(Response response, BaseRespMsg msg) {

                if (msg.getStatus() == BaseRespMsg.STATUS_SUCCESS) {
                    ToastUtils.show(AddressAddActivity.this, "保存成功");
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    private void addressAdd() {


        String phone = edittxtPhone.getText().toString();
        String consignee = edittxtConsignee.getText().toString();
        String addr = txtAddress.getText().toString() + edittxtAdd.getText().toString();

        if (phone.length() != 11) {
            ToastUtils.show(this, "手机号格式不正确");
            return;
        }


        Map<String, Object> params = new HashMap<>();
        params.put("user_id", App.getInstance().getUser().getId());
        params.put("consignee", consignee);
        params.put("phone", phone);
        params.put("addr", addr);
        params.put("zip_code", "000000");
        helper.post(Contans.API.ADDRESS_CREATE, params, new SpotsCallBack<BaseRespMsg>(this) {
            @Override
            public void onSuccess(Response response, BaseRespMsg msg) {

                if (msg.getStatus() == BaseRespMsg.STATUS_SUCCESS) {
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    @Override
    public void initData() {
        initJsonData();
        initOptionPicker();
    }

    @OnClick(R.id.ll_city_picker)
    public void showCityPicker() {
        pvOptions.show();
    }


    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */

        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()
                        + options2Items.get(options1).get(options2)
                        + options3Items.get(options1).get(options2).get(options3);
                txtAddress.setText(tx);
            }
        })
                .setTitleText("城市选择")
                .setSelectOptions(0, 0, 0)//默认选中项
                .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<Province> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }


    public ArrayList<Province> parseData(String result) {//Gson 解析
        ArrayList<Province> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                Province entity = gson.fromJson(data.optJSONObject(i).toString(), Province.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
